package com.price.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PaintFlagsDrawFilter
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.price.common.extend.logError
import com.zp.common.R
import kotlin.math.log
import kotlin.math.max
import kotlin.math.min

//仪表盘进度
class ArcProgressBar(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    View(context, attrs, defStyleAttr) {

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null)

    private var diameter = 500f //直径

    private var centerX = 0f //圆心X坐标

    private var centerY = 0f //圆心Y坐标


    private lateinit var allArcPaint: Paint
    private lateinit var progressPaint: Paint
    private lateinit var vTextPaint: Paint
    private lateinit var hintPaint: Paint

    private lateinit var dialPaint: Paint

    private lateinit var bgRect: RectF

    private var mLineRound=true
    private var mShowAnima = true
    private var progressAnimator: ValueAnimator? = null
    private var mDrawFilter: PaintFlagsDrawFilter? = null


    private var startDial:Int=13
    private var endDial:Int=27

    var startAngle = 155f
        set(value) {
            field=value
            sweepAngle=(270-field)*2

            endDial=(startAngle+90).div(9).toInt()
            startDial=endDial-(360-sweepAngle).div(9).toInt()
        }

    private var sweepAngle = 230f

    private var currentAngle = 0f
    private var lastAngle = 0f
    private var maxValues = 60f
    private var curValues = 0f
    private var bgArcWidth = dipToPx(2f).toFloat()
    private var progressWidth = dipToPx(10f).toFloat()
    private var textSize = dipToPx(60f).toFloat()
    private var hintSize = dipToPx(15f).toFloat()


    private val aniSpeed = 1000

    private val padding = dipToPx(4f)


    private var bgArcColor = Color.GRAY //圆圈背景色（画笔颜色）
    private var progressColor = Color.GREEN

    private var titleString: String? = null
    private var unitString: String? = null

    private var isNeedContent = true

    private var showDial = true
    private var dialColor= Color.WHITE
    private var dialWidth= dipToPx(2f).toFloat()


    // sweepAngle / maxValues 的值
    private var k = 0f

    init {
        initCofig(context, attrs)
    }


    /**
     * 初始化布局配置
     * @param context
     * @param attrs
     */
    private fun initCofig(context: Context, attrs: AttributeSet?) {
        if (attrs == null) {
            return
        }
        val a = context.obtainStyledAttributes(attrs, R.styleable.ArcProgressBar)

        bgArcWidth =
            a.getDimension(R.styleable.ArcProgressBar_arc_width, dipToPx(15f).toFloat())
        bgArcColor = a.getColor(R.styleable.ArcProgressBar_arc_color, Color.GRAY)


        progressWidth =
            a.getDimension(R.styleable.ArcProgressBar_progress_width, dipToPx(10f).toFloat())
        progressColor = a.getColor(R.styleable.ArcProgressBar_progress_color, Color.GREEN)

        isNeedContent = a.getBoolean(R.styleable.ArcProgressBar_show_content, true)

        textSize = a.getDimension(R.styleable.ArcProgressBar_text_size, dipToPx(60f).toFloat())
        unitString = a.getString(R.styleable.ArcProgressBar_string_unit)
        titleString = a.getString(R.styleable.ArcProgressBar_string_title)
        curValues = a.getFloat(R.styleable.ArcProgressBar_current_value, 0f)
        maxValues = a.getFloat(R.styleable.ArcProgressBar_max_value, 60f)
        mShowAnima = a.getBoolean(R.styleable.ArcProgressBar_show_anima, true)
        mLineRound=a.getBoolean(R.styleable.ArcProgressBar_show_round,true)

        startAngle=a.getFloat(R.styleable.ArcProgressBar_start_angle,155f)
        showDial = a.getBoolean(R.styleable.ArcProgressBar_show_dial, true)
        dialColor=a.getColor(R.styleable.ArcProgressBar_dial_color,Color.WHITE)
        dialWidth=a.getDimension(R.styleable.ArcProgressBar_dial_width,dipToPx(2f).toFloat())

        setCurrentValues(curValues)
        setMaxValues(maxValues)
        a.recycle()
    }


    private fun initView() {

        //弧形的矩阵区域
        bgRect = RectF()
        bgRect.top = centerY - diameter / 2
        bgRect.left = centerX - diameter / 2
        bgRect.right = centerX + diameter / 2
        bgRect.bottom = centerY + diameter / 2

        //外部刻度线
        dialPaint = Paint()
        dialPaint.color = dialColor
        dialPaint.strokeWidth = dialWidth

//整个弧形
        allArcPaint = Paint()
        allArcPaint.isAntiAlias = true
        allArcPaint.style = Paint.Style.STROKE
        allArcPaint.strokeWidth = bgArcWidth
        allArcPaint.color = bgArcColor
        allArcPaint.strokeCap = if(mLineRound) {Paint.Cap.ROUND}else{Paint.Cap.SQUARE}
//当前进度的弧形
        progressPaint = Paint()
        progressPaint.isAntiAlias = true
        progressPaint.style = Paint.Style.STROKE
        progressPaint.strokeWidth = progressWidth
        progressPaint.color = progressColor
        progressPaint.strokeCap = if(mLineRound) {Paint.Cap.ROUND}else{Paint.Cap.SQUARE}

//内容显示文字
        vTextPaint = Paint()
        vTextPaint.textSize = textSize
        vTextPaint.color = progressColor
        vTextPaint.textAlign = Paint.Align.CENTER

        //显示标题文字
        //显示单位文字
        hintPaint = Paint()
        hintPaint.textSize = hintSize
        hintPaint.color = bgArcColor
        hintPaint.textAlign = Paint.Align.CENTER


        mDrawFilter = PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)


    }

    override fun onDraw(canvas: Canvas) {
        //抗锯齿
        canvas.drawFilter = mDrawFilter

        //整个弧
        canvas.drawArc(bgRect, startAngle, sweepAngle, false, allArcPaint)

        if (showDial) {
            //画刻度线
            for (i in 0..39) {
                if (i in (startDial + 1)..<endDial) {
                    canvas.rotate(9f, centerX, centerY)
                    continue
                }

                canvas.drawLine(
                    centerX,
                    centerY - diameter / 2 - bgArcWidth / 3,
                    centerX,
                    centerY - diameter / 2 + bgArcWidth / 3,
                    dialPaint
                )

                canvas.rotate(9f, centerX, centerY)
            }
        }
        valueChangeListener?.onValueChange(curValues.toInt())
        //当前进度
        canvas.drawArc(bgRect, startAngle, currentAngle, false, progressPaint)


        if (isNeedContent) {
            canvas.drawText(
                String.format("%.0f", curValues), centerX, centerY + textSize / 3,
                vTextPaint
            )
        }
        if (!unitString.isNullOrBlank()) {
            canvas.drawText(unitString!!, centerX, centerY + 4 * textSize / 5, hintPaint)
        }

        if (!titleString.isNullOrBlank()) {
            canvas.drawText(titleString!!, centerX, centerY - 2 * textSize / 3, hintPaint)
        }

    }

    /**
     * 设置最大值
     * @param maxValues
     */
    fun setMaxValues(maxValues: Float) {
        this.maxValues = maxValues
        k = sweepAngle / maxValues
        invalidate()
    }

    /**
     * 设置当前值
     * @param currentValue
     */
    fun setCurrentValues(currentValue: Float) {
        var cv = currentValue
        if (cv > maxValues) {
            cv = maxValues
        }else if (cv < 0) {
            cv = 0f
        }
        curValues = cv
        lastAngle = currentAngle

        k = sweepAngle / maxValues
        if (mShowAnima) {
            setAnimation(lastAngle, curValues * k, aniSpeed)
        } else {
            currentAngle = curValues * k
            invalidate()
        }
    }

    /**
     * 设置整个圆弧宽度
     * @param bgArcWidth
     */
    fun setBgArcWidth(bgArcWidth: Int) {
        this.bgArcWidth = bgArcWidth.toFloat()
        invalidate()
    }

    /**
     * 设置进度宽度
     * @param progressWidth
     */
    fun setProgressWidth(progressWidth: Int) {
        this.progressWidth = progressWidth.toFloat()
        invalidate()
    }

    /**
     * 设置速度文字大小
     * @param textSize
     */
    fun setTextSize(textSize: Int) {
        this.textSize = textSize.toFloat()
        invalidate()
    }

    /**
     * 设置单位文字大小
     * @param hintSize
     */
    fun setHintSize(hintSize: Int) {
        this.hintSize = hintSize.toFloat()
        invalidate()
    }

    /**
     * 设置单位文字
     * @param hintString
     */
    fun setUnit(hintString: String?) {
        this.unitString = hintString
        invalidate()
    }

    /**
     * 设置标题
     * @param title
     */
    private fun setTitle(title: String) {
        titleString = title
        invalidate()
    }


    /**
     * 为进度设置动画
     * @param last
     * @param current
     */
    private fun setAnimation(last: Float, current: Float, length: Int) {

        progressAnimator = ValueAnimator.ofFloat(last, current)
        progressAnimator!!.duration = length.toLong()
        progressAnimator!!.setTarget(currentAngle)
        progressAnimator!!.addUpdateListener { animation ->
            currentAngle = animation.animatedValue as Float
            curValues = currentAngle / k

            postInvalidate()
        }
        progressAnimator!!.start()
    }

    /**
     * dip 转换成px
     * @param dip
     * @return
     */
    private fun dipToPx(dip: Float): Int {
        val density = context.resources.displayMetrics.density
        return (dip * density + 0.5f * if (dip >= 0) 1 else -1).toInt()
    }


    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

        diameter = min(width, height) - padding - max(bgArcWidth, progressWidth)

        //圆心
        centerX = width / 2f
        centerY = height / 2f

        initView()
    }

    var valueChangeListener:ValueChangeListener?=null

    interface ValueChangeListener{
        fun onValueChange(value:Int)
    }
}